﻿using System;
using System.Web;
using TrafficArchives.Common;
using TrafficArchives.DataAccess;
using TrafficArchives.Models;
using TrafficArchives.Utilities;

namespace TrafficArchives.Logs
{
    public class LogWriter
    {
        /// <summary>
        /// 写入日志。
        /// </summary>
        /// <param name="log"></param>
        public static void Writer(LogInfo log)
        {
            Default.CheckLogin();

            var request = new Request();
            request.Items.Add(new Condition { FieldName = "LOG_ID", Operator = ConditionOperator.Equal, Values = new object[]{"null"}});
            var db = new LogBb();
            var data = db.GetData(request).Data;
            var newRow = data.NewRow();
            newRow["LOG_ID"] = Guid.NewGuid().ToString();
            newRow["CZR_ID"] = LoginUser.Current.UserId;
            newRow["CZTYPENAME"] = log.Type.ToString();
            newRow["CZTIME"] = DateTime.Now;
            newRow["CZMACHINEID"] = GetIp();
            newRow["BCZRNAME"] = log.OwerName;
            newRow["BCZRJSZH"] = log.OwerDriverNo;
            newRow["BCZRDABH"] = log.OwerArchiveNo;
            newRow["BCZRSFZH"] = log.Identity;
            data.Rows.Add(newRow);
            db.Add(data);
        }

        public static string GetIp()
        {
            string userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            if (string.IsNullOrEmpty(userHostAddress))
            {
                userHostAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            }
            if (string.IsNullOrEmpty(userHostAddress))
            {
                userHostAddress = HttpContext.Current.Request.UserHostAddress;
            }
            if (!string.IsNullOrEmpty(userHostAddress) && IsIp(userHostAddress))
            {
                return userHostAddress;
            }
            return "127.0.0.1";
        }

        public static bool IsIp(string ip)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(ip,@"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
    }

    public enum LogType
    {
        用户信息添加,
        用户信息修改,
        初始化密码,
        添加单位,
        修改单位,
        信誉档案查询,
        添加信誉档案,
        修改信誉档案,
        取消信誉报告
    }
}